package cn.sheep.dolphin.tag

import ch.hsr.geohash.GeoHash
import org.apache.commons.lang.StringUtils
import org.apache.spark.sql.Row
import redis.clients.jedis.Jedis
import cn.sheep.dolphin.bean.RichString._

/** 设备相关的标签 -
  * author: old sheep
  * QQ: 64341393 
  * Created 2018/12/2
  */
object Tags4Device extends Tags {
	/**
	  * 定义个标签接口
	  *
	  * @param args
	  * @return
	  */
	override def makeTags(args: Any*): Map[String, Int] = {
		var tagMap = Map[String, Int]()

		// 解析参数
		val row = args(0).asInstanceOf[Row]
		val jedis = args(1).asInstanceOf[Jedis]


		// APP
		val appName = row.getAs[String]("appname")
		if (StringUtils.isEmpty(appName)) {
			val appId = row.getAs[String]("appid")
			if (StringUtils.isNotEmpty(appId)) {
				val appNameRedis = jedis.hget("appdict", appId)
				if (StringUtils.isNotEmpty(appNameRedis)) tagMap += "APP" + appNameRedis -> 1
				else tagMap += "APP" + appId -> 1
			}
		} else tagMap += "APP" + appName -> 1


		// 操作系统
		val clientOS = row.getAs[Int]("client")
		clientOS match {
			case 1 => tagMap += "D00010001" -> 1
			case 2 => tagMap += "D00010002" -> 1
			case 3 => tagMap += "D00010003" -> 1
			case _ =>
		}

		// 网络类型
		val network = row.getAs[String]("networkmannername")
		network.toUpperCase match {
			case "WIFI" => tagMap += "D00020001" -> 1
			case "2G" => tagMap += "D00020002" -> 1
			case "3G" => tagMap += "D00020003" -> 1
			case "4G" => tagMap += "D00020004" -> 1
			case _ =>
		}

		// 运营商
		val isp = row.getAs[String]("ispname")
		isp match {
			case "移动" => tagMap += "D00030001" -> 1
			case "联通" => tagMap += "D00030002" -> 1
			case "电信" => tagMap += "D00030003" -> 1
			case _ =>
		}


		// 地域
		val province = row.getAs[String]("provincename")
		val city = row.getAs[String]("cityname")
		if (StringUtils.isNotEmpty(province)) tagMap += "ZP" + province -> 1
		if (StringUtils.isNotEmpty(city)) tagMap += "ZC" + city -> 1

		// 商圈
		val lat = row.getAs[String]("lat").toDoublePlus
		val lng = row.getAs[String]("long").toDoublePlus
		if (lng<=136 && lng>=73 && lat>=3 && lat<=54) {
			try {
				val geoCode = GeoHash.withCharacterPrecision(lat, lng, 8).toBase32
				/**
					* 判断是否能查到商圈信息，如果能则返回，不能不返回，
					* 或者返回默认值，方便以后统计，
					* 或者去百度等其他地图服务查询，
					* 可扩展，最好对此处单独封装一个方法后再调用
					*/
				val business = jedis.hget("businessdict", geoCode)
				if (StringUtils.isNotEmpty(business)) tagMap += "BS" + business -> 1
			} catch {
				case e:Exception => e.printStackTrace()
			}
		}

		tagMap
	}
}
